<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统信息监控面板</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
            color: #333;
        }
        
        .dashboard {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .header h1 {
            color: #2c3e50;
            margin-bottom: 10px;
        }
        
        .grid-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .card {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            padding: 20px;
            transition: transform 0.3s ease;
        }
        
        .card:hover {
            transform: translateY(-5px);
        }
        
        .card h2 {
            margin-top: 0;
            color: #3498db;
            font-size: 18px;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        
        .value-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .gauge-container {
            position: relative;
            width: 200px;
            height: 100px;
            margin: 0 auto 20px;
        }
        
        .network-list, .disk-list {
            margin-top: 10px;
        }
        
        .network-item, .disk-item {
            padding: 8px 0;
            border-bottom: 1px solid #eee;
        }
        
        .last-row {
            border-bottom: none;
        }
        
        .full-width {
            grid-column: 1 / -1;
        }
        
        .last-updated {
            text-align: right;
            font-size: 12px;
            color: #7f8c8d;
            margin-top: 20px;
        }

        .trend-chart {
            height: 200px;
            margin-top: 20px;
        }
        
        @media (max-width: 768px) {
            .grid-container {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="dashboard">
        <div class="header">
            <h1>系统信息监控面板</h1>
            <p>实时监控您的系统状态</p>
        </div>
        
        <div class="grid-container">
            <div class="card">
                <h2>CPU 使用率</h2>
                <div class="gauge-container">
                    <canvas id="cpuGauge"></canvas>
                </div>
                <div class="value-container">
                    <span id="cpuUsageValue">--%</span>
                    <span id="cpuModel">加载中...</span>
                </div>
                <div class="trend-chart">
                    <canvas id="cpuTrendChart"></canvas>
                </div>
            </div>
            
            <div class="card">
                <h2>GPU 使用率</h2>
                <div class="gauge-container">
                    <canvas id="gpuGauge"></canvas>
                </div>
                <div class="value-container">
                    <span id="gpuUsageValue">--%</span>
                    <span id="gpuModel">加载中...</span>
                </div>
                <div class="trend-chart">
                    <canvas id="gpuTrendChart"></canvas>
                </div>
            </div>
            
            <div class="card">
                <h2>内存使用</h2>
                <div class="gauge-container">
                    <canvas id="memoryGauge"></canvas>
                </div>
                <div class="value-container">
                    <span id="memoryUsageValue">--%</span>
                    <span id="ram">加载中...</span>
                </div>
                <div class="trend-chart">
                    <canvas id="memoryTrendChart"></canvas>
                </div>
            </div>
            
            <div class="card full-width">
                <h2>磁盘使用</h2>
                <div id="diskUsageChartContainer" style="height: 200px;">
                    <canvas id="diskUsageChart"></canvas>
                </div>
                <div class="disk-list" id="diskList">
                    <!-- 磁盘列表将在这里填充 -->
                </div>
            </div>
            
            <div class="card full-width">
                <h2>网络速度</h2>
                <div id="networkSpeedChartContainer" style="height: 200px;">
                    <canvas id="networkSpeedChart"></canvas>
                </div>
                <div class="network-list" id="networkList">
                    <!-- 网络速度列表将在这里填充 -->
                </div>
            </div>
        </div>
        
        <div class="last-updated" id="lastUpdated">
            最后更新: --
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        // 存储历史数据用于趋势图
        const historyData = {
            cpuUsage: [],
            gpuUsage: [],
            memoryUsage: [],
            networkDownload: [],
            networkUpload: [],
            timestamps: []
        };

        // 存储图表的引用
        let cpuGauge, gpuGauge, memoryGauge, diskUsageChart;
        let cpuTrendChart, gpuTrendChart, memoryTrendChart, networkSpeedTrendChart;

        // 确保DOM已完全加载
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化图表
            initializeCharts();

            // 初始加载数据
            updateSystemInfo();

            // 每1秒更新一次数据
            setInterval(updateSystemInfo, 1000);
        });

        // 初始化所有图表
        function initializeCharts() {
            // 初始化CPU仪表盘
            cpuGauge = new Chart(
                document.getElementById('cpuGauge'),
                {
                    type: 'doughnut',
                    data: {
                        datasets: [{
                            data: [0, 100],
                            backgroundColor: [
                                '#3498db',
                                '#ecf0f1'
                            ],
                            borderWidth: 0
                        }]
                    },
                    options: {
                        cutout: '80%',
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            },
                            tooltip: {
                                enabled: false
                            }
                        },
                        circumference: 180,
                        rotation: 270
                    }
                }
            );

            // 初始化GPU仪表盘
            gpuGauge = new Chart(
                document.getElementById('gpuGauge'),
                {
                    type: 'doughnut',
                    data: {
                        datasets: [{
                            data: [0, 100],
                            backgroundColor: [
                                '#9b59b6',
                                '#ecf0f1'
                            ],
                            borderWidth: 0
                        }]
                    },
                    options: {
                        cutout: '80%',
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            },
                            tooltip: {
                                enabled: false
                            }
                        },
                        circumference: 180,
                        rotation: 270
                    }
                }
            );

            // 初始化内存仪表盘
            memoryGauge = new Chart(
                document.getElementById('memoryGauge'),
                {
                    type: 'doughnut',
                    data: {
                        datasets: [{
                            data: [0, 100],
                            backgroundColor: [
                                '#2ecc71',
                                '#ecf0f1'
                            ],
                            borderWidth: 0
                        }]
                    },
                    options: {
                        cutout: '80%',
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            },
                            tooltip: {
                                enabled: false
                            }
                        },
                        circumference: 180,
                        rotation: 270
                    }
                }
            );

            // 初始化磁盘使用图表
            diskUsageChart = new Chart(
                document.getElementById('diskUsageChart'),
                {
                    type: 'bar',
                    data: {
                        labels: [],
                        datasets: [{
                            label: '已使用空间',
                            backgroundColor: '#3498db',
                            data: []
                        }]
                    },
                    options: {
                        indexAxis: 'y',
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            }
                        },
                        scales: {
                            x: {
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: '已使用空间 (GB)'
                                }
                            }
                        }
                    }
                }
            );

            // 初始化CPU趋势图
            cpuTrendChart = new Chart(
                document.getElementById('cpuTrendChart'),
                {
                    type: 'line',
                    data: {
                        labels: [],
                        datasets: [{
                            label: 'CPU 使用率',
                            borderColor: '#3498db',
                            backgroundColor: 'rgba(52, 152, 219, 0.1)',
                            data: [],
                            tension: 0.4,
                            fill: true
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: true,
                                max: 100,
                                title: {
                                    display: true,
                                    text: '使用率 (%)'
                                }
                            }
                        }
                    }
                }
            );

            // 初始化GPU趋势图
            gpuTrendChart = new Chart(
                document.getElementById('gpuTrendChart'),
                {
                    type: 'line',
                    data: {
                        labels: [],
                        datasets: [{
                            label: 'GPU 使用率',
                            borderColor: '#9b59b6',
                            backgroundColor: 'rgba(155, 89, 182, 0.1)',
                            data: [],
                            tension: 0.4,
                            fill: true
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: true,
                                max: 100,
                                title: {
                                    display: true,
                                    text: '使用率 (%)'
                                }
                            }
                        }
                    }
                }
            );

            // 初始化内存趋势图
            memoryTrendChart = new Chart(
                document.getElementById('memoryTrendChart'),
                {
                    type: 'line',
                    data: {
                        labels: [],
                        datasets: [{
                            label: '内存使用率',
                            borderColor: '#2ecc71',
                            backgroundColor: 'rgba(46, 204, 113, 0.1)',
                            data: [],
                            tension: 0.4,
                            fill: true
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: true,
                                max: 100,
                                title: {
                                    display: true,
                                    text: '使用率 (%)'
                                }
                            }
                        }
                    }
                }
            );

            // 初始化网络速度趋势图
            networkSpeedTrendChart = new Chart(
                document.getElementById('networkSpeedChart'),
                {
                    type: 'line',
                    data: {
                        labels: [],
                        datasets: [
                            {
                                label: '下载速度',
                                borderColor: '#3498db',
                                backgroundColor: 'rgba(52, 152, 219, 0.1)',
                                data: [],
                                tension: 0.4,
                                fill: true
                            },
                            {
                                label: '上传速度',
                                borderColor: '#e74c3c',
                                backgroundColor: 'rgba(231, 76, 60, 0.1)',
                                data: [],
                                tension: 0.4,
                                fill: true
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: '速度 (KB/s)'
                                }
                            }
                        }
                    }
                }
            );
        }

        // 格式化时间戳
        function formatDate(date) {
            const now = new Date();
            const diff = Math.floor((now - date) / 1000);
            
            if (diff < 60) {
                return `${diff}秒前`;
            } else if (diff < 3600) {
                return `${Math.floor(diff / 60)}分钟前`;
            } else if (diff < 86400) {
                return `${Math.floor(diff / 3600)}小时前`;
            } else {
                return `${Math.floor(diff / 86400)}天前`;
            }
        }

        // 更新系统信息
        async function updateSystemInfo() {
            try {
                const response = await fetch('/system-info');
                const data = await response.json();
                
                // 更新CPU信息
                const cpuUsage = parseFloat(data.cpu_usage).toFixed(2);
                document.getElementById('cpuUsageValue').textContent = `${cpuUsage}%`;
                document.getElementById('cpuModel').textContent = data.cpu_model;
                
                // 更新CPU仪表盘
                cpuGauge.data.datasets[0].data = [parseFloat(cpuUsage), 100 - parseFloat(cpuUsage)];
                cpuGauge.update();
                
                // 更新GPU信息
                const gpuUsage = parseFloat(data.gpu_usage).toFixed(2);
                document.getElementById('gpuUsageValue').textContent = `${gpuUsage}%`;
                document.getElementById('gpuModel').textContent = data.gpu_model;
                
                // 更新GPU仪表盘
                gpuGauge.data.datasets[0].data = [parseFloat(gpuUsage), 100 - parseFloat(gpuUsage)];
                gpuGauge.update();
                
                // 更新内存信息
                const memoryInfo = data.memory_usage.split(' / ');
                const memoryUsed = parseFloat(memoryInfo[0].replace(' GB', '')).toFixed(2);
                const memoryTotal = parseFloat(memoryInfo[1].replace(' GB', '')).toFixed(2);
                const memoryPercent = (memoryUsed / memoryTotal * 100).toFixed(2);
                document.getElementById('memoryUsageValue').textContent = `${memoryPercent}% (${memoryUsed} GB / ${memoryTotal} GB)`;
                document.getElementById('ram').textContent = data.ram;
                
                // 更新内存仪表盘
                memoryGauge.data.datasets[0].data = [parseFloat(memoryPercent), 100 - parseFloat(memoryPercent)];
                memoryGauge.update();
                
                // 更新磁盘信息
                diskUsageChart.data.labels = data.disk_usage.map(item => item.split(': ')[0]);
                diskUsageChart.data.datasets[0].data = data.disk_usage.map(item => {
                    const values = item.split(': ')[1].split(' / ');
                    return parseFloat(values[0].replace(' GB', ''));
                });
                diskUsageChart.update();
                
                // 更新磁盘列表
                const diskListElement = document.getElementById('diskList');
                diskListElement.innerHTML = '';
                data.disk_usage.forEach(disk => {
                    const item = document.createElement('div');
                    item.className = 'disk-item';
                    item.textContent = disk;
                    diskListElement.appendChild(item);
                });
                
                // 更新网络速度信息
                const networkListElement = document.getElementById('networkList');
                networkListElement.innerHTML = '';
                data.network_speed.forEach(speed => {
                    const item = document.createElement('div');
                    item.className = 'network-item';
                    item.textContent = speed;
                    networkListElement.appendChild(item);
                });
                
                // 提取网络速度值
                data.network_speed.forEach(speed => {
                    // 匹配下载速度
                    const downloadMatch = speed.match(/▼([\d.]+)(\w+)\/s/);
                    // 匹配上传速度
                    const uploadMatch = speed.match(/▲([\d.]+)(\w+)\/s/);
                    
                    let download = 0;
                    let upload = 0;
                    
                    // 处理下载速度
                    if (downloadMatch) {
                        const value = parseFloat(downloadMatch[1]);
                        const unit = downloadMatch[2];
                        if (unit === 'MB') {
                            download = value * 1024; // MB to KB
                        } else if (unit === 'KB') {
                            download = value;
                        }
                    }
                 

                    // 处理上传速度
                    if (uploadMatch) {
                        const value = parseFloat(uploadMatch[1]);
                        const unit = uploadMatch[2];
                        if (unit === 'MB') {
                            upload = value * 1024; // MB to KB
                        } else if (unit === 'KB') {
                            upload = value;
                        }
                    }

                    // console.log("下载速度"); 
                    // console.log(downloadMatch); 
                    // console.log(download); 
                    // console.log("上传速度"); 
                    // console.log(uploadMatch); 
                    // console.log(upload); 
                    
                    historyData.networkDownload.push(download);
                    historyData.networkUpload.push(upload);
                });
                
                // 更新趋势图数据
                const timestamp = new Date();
                // historyData.timestamps.push(formatDate(timestamp));
                historyData.timestamps.push("↑");
                historyData.cpuUsage.push(parseFloat(cpuUsage));
                historyData.gpuUsage.push(parseFloat(gpuUsage));
                historyData.memoryUsage.push(parseFloat(memoryPercent));
                
                // 限制历史数据点数量
                if (historyData.timestamps.length > 10) {
                    historyData.timestamps.shift();
                    historyData.cpuUsage.shift();
                    historyData.gpuUsage.shift();
                    historyData.memoryUsage.shift();
                    historyData.networkDownload.shift();
                    historyData.networkUpload.shift();
                }
                
                // 更新趋势图
                cpuTrendChart.data.labels = historyData.timestamps;
                cpuTrendChart.data.datasets[0].data = historyData.cpuUsage;
                cpuTrendChart.update();
                
                gpuTrendChart.data.labels = historyData.timestamps;
                gpuTrendChart.data.datasets[0].data = historyData.gpuUsage;
                gpuTrendChart.update();
                
                memoryTrendChart.data.labels = historyData.timestamps;
                memoryTrendChart.data.datasets[0].data = historyData.memoryUsage;
                memoryTrendChart.update();
                
                networkSpeedTrendChart.data.labels = historyData.timestamps;
                networkSpeedTrendChart.data.datasets[0].data = historyData.networkDownload;
                networkSpeedTrendChart.data.datasets[1].data = historyData.networkUpload;
                networkSpeedTrendChart.update();
                
                // 更新最后更新时间
                document.getElementById('lastUpdated').textContent = `最后更新: ${formatDate(timestamp)}`;
                
            } catch (error) {
                console.error('获取系统信息失败:', error);
                document.getElementById('lastUpdated').textContent = `最后更新: 获取失败`;
            }
        }
    </script>
</body>
</html>